package com.snxun.browser_light.module.home;

import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.annotation.SuppressLint;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.core.view.GestureDetectorCompat;
import androidx.viewpager.widget.ViewPager;

import com.lodz.android.imageloaderkt.ImageLoader;
import com.lodz.android.pandora.base.activity.AbsActivity;
import com.snxun.browser_light.R;
import com.snxun.browser_light.adapter.home.MainViewPagerAdapeter;
import com.snxun.browser_light.bean.AppInfoBean;
import com.snxun.browser_light.widget.eventbus.BaseEvent;
import com.snxun.browser_light.widget.eventbus.ChangeTitleEvent;
import com.snxun.browser_light.widget.eventbus.EventType;
import com.snxun.browser_light.widget.eventbus.MessageEvent;
import com.snxun.browser_light.widget.eventbus.SlideEvent;
import com.snxun.browser_light.widget.eventbus.ZoomEvent;
import com.snxun.browser_light.widget.gesturedetector.SimpleOnGestureListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;

import static android.widget.RelativeLayout.CENTER_IN_PARENT;

public class MainActivity extends AbsActivity {


    /**
     * 底部添加按钮
     */
    @BindView(R.id.bottom_item_add)
    ImageView mBottomAddBtn;

    /**
     * viewpager
     */
    @BindView(R.id.main_viewpager)
    ViewPager mViewPager;

    /**
     * viewapger适配器
     */
    MainViewPagerAdapeter mMainViewPagerAdapeter;

    /**
     * app列表数据
     */
    private ArrayList<AppInfoBean> mViewPagerDataList;

    /**
     * 底部打开多窗口按钮
     */
    @BindView(R.id.bottom_item_multi)
    ImageView mBottomMultiBtn;

    /**
     * 存放viewpager的布局
     */
    @BindView(R.id.viewpager_layout)
    LinearLayout mViewpagerLayout;

    /**
     * 主界面底部布局
     */
    @BindView(R.id.bottom_layout)
    LinearLayout mBottomMainMenuLayout;

    /**
     * 多窗口底部布局layout
     */
    @BindView(R.id.botttom_manage_menu_layout)
    LinearLayout mBottomManageMenuLayout;

    @BindView(R.id.main_layout)
    RelativeLayout mMainLayout;
    /**
     * 多窗口底部返回按钮
     */
    @BindView(R.id.bottom_item_back)
    ImageView mBottomBackBtn;

    /**
     * 底部退出应用程序按钮
     */
    @BindView(R.id.bottom_item_exit)
    ImageView mBottomExitBtn;
    /**
     * 底部清空窗口按钮
     */
    @BindView(R.id.bottom_item_clear)
    ImageView mBottomClearBtn;
    /**
     * 底部左下角显示窗口对应的图标
     */
    @BindView(R.id.bottom_item_title_img)
    ImageView mBottomTitleIcon;
    /**
     * 底部左下角显示窗口对应的标题
     */
    @BindView(R.id.bottom_item_title_tv)
    TextView mBottomTitleTv;

    private DisplayMetrics mDisplayMetrics;
    private GestureDetectorCompat mDetector;
    private SimpleOnGestureListener mSimpleOnGestureListener;

    @Override
    protected int getAbsLayoutId() {
        return R.layout.activity_main;
    }


    @Override
    protected void findViews(@Nullable Bundle savedInstanceState) {
        super.findViews(savedInstanceState);
        ButterKnife.bind(this);
        initViewPager();
        initGestureUtil();

    }


    /**
     * 初始化手势监听相关
     */
    private void initGestureUtil() {
        mDisplayMetrics = getResources().getDisplayMetrics();
        mSimpleOnGestureListener = new SimpleOnGestureListener();
        mDetector = new GestureDetectorCompat(this, mSimpleOnGestureListener);
    }

    /**
     * 初始化viewPager
     */
    private void initViewPager() {
        mMainViewPagerAdapeter = new MainViewPagerAdapeter(getSupportFragmentManager());
        mViewPager.setOffscreenPageLimit(10);
        mViewPager.setAdapter(mMainViewPagerAdapeter);
    }


    @Override
    protected void initData() {
        super.initData();
        initViewPagerData();
    }

    /**
     * 创建模拟的app列表数据
     */
    private void initViewPagerData() {
        mViewPagerDataList = new ArrayList<>();
        AppInfoBean infoBean = new AppInfoBean();
        infoBean.appIconUrl = "https://bkimg.cdn.bcebos" +
                ".com/pic/279759ee3d6d55fb22bcda0961224f4a20a4dda3?x-bce-process=image/resize," +
                "m_lfit,w_268,limit_1/format,f_jpg";
        infoBean.appName = "百度";
        infoBean.appLoadUrl = "https://www.baidu.com";
        mViewPagerDataList.add(infoBean);

        AppInfoBean infoBean2 = new AppInfoBean();
        infoBean2.appIconUrl = "https://bkimg.cdn.bcebos" +
                ".com/pic/c2fdfc039245d688d43f28dea2886a1ed21b0ef48e3d?x-bce-process=image" +
                "/resize,m_lfit,w_268,limit_1/format,f_jpg";
        infoBean2.appName = "网易";
        infoBean2.appLoadUrl = "https://www.163.com";
        mViewPagerDataList.add(infoBean2);

        mMainViewPagerAdapeter.addData(WebViewFragment.newInstance(mViewPagerDataList, String.valueOf(UUID.randomUUID())));
    }


    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void setListeners() {
        super.setListeners();

        mMainLayout.setOnTouchListener((v, event) -> {
            mDetector.onTouchEvent(event);
            return true;
        });
        //底部添加按钮监听
        mBottomAddBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMainViewPagerAdapeter.addData(WebViewFragment.newInstance(mViewPagerDataList, String.valueOf(UUID.randomUUID())));
                mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1, true);
            }
        });
        //底部多窗口按钮监听
        mBottomMultiBtn.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onClick(View v) {
                changeWindowSize();
            }
        });
        //底部返回按钮监听
        mBottomBackBtn.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onClick(View v) {
                changeWindowSize();
            }
        });
        //底部离开按钮监听
        mBottomExitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //底部清空按钮监听
        mBottomClearBtn.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onClick(View v) {
                mMainViewPagerAdapeter.clearDataAndCreateNewFragment(WebViewFragment.newInstance(mViewPagerDataList, String.valueOf(UUID.randomUUID())));
                mViewPager.setCurrentItem(0, true);
                //自动将缩放状态还原，避免fragment的view还未被加载，导致点击事件无法触发
                changeWindowSize();
            }
        });
    }

    /**
     * 窗口缩放
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    @SuppressLint("UseCompatLoadingForDrawables")
    private void changeWindowSize() {
        int viewpagerWidth = mViewpagerLayout.getWidth();
        if (mDisplayMetrics.widthPixels - viewpagerWidth < 5) {
            mBottomMainMenuLayout.setVisibility(View.GONE);
            mBottomManageMenuLayout.setVisibility(View.VISIBLE);

            mViewPager.setPageMargin(40);
            mViewpagerLayout.setGravity(CENTER_IN_PARENT);

            //缩小
            PropertyValuesHolder pvhX = PropertyValuesHolder.ofFloat("scaleX", 1f, 0.8f);
            PropertyValuesHolder pvhY = PropertyValuesHolder.ofFloat("scaleY", 1f, 0.8f);
            ObjectAnimator scale = ObjectAnimator.ofPropertyValuesHolder(mViewPager, pvhX, pvhY);
            scale.setDuration(30);
            scale.start();

            RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(mDisplayMetrics.widthPixels * 8 / 10, mDisplayMetrics.heightPixels * 8 / 10);
            param.addRule(CENTER_IN_PARENT);
            mViewpagerLayout.setLayoutParams(param);
            mMainLayout.setBackgroundColor(getColor(R.color.color_80C0C0C0));
            mSimpleOnGestureListener.setViewPagePosition(mViewPager.getWidth(), mViewPager.getHeight());
            EventBus.getDefault().post(new MessageEvent(EventType.SHOW_FRAGMENT_DELETE_BTN));
        } else {
            mViewPager.setPageMargin(0);
            //放大到原来样子
            PropertyValuesHolder pvhX = PropertyValuesHolder.ofFloat("scaleX", 0.8f, 1f);
            PropertyValuesHolder pvhY = PropertyValuesHolder.ofFloat("scaleY", 0.8f, 1f);
            ObjectAnimator scale = ObjectAnimator.ofPropertyValuesHolder(mViewPager, pvhX, pvhY);
            scale.setDuration(30);
            scale.start();
            RelativeLayout.LayoutParams Rlparam2 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            Rlparam2.addRule(CENTER_IN_PARENT);
            mViewpagerLayout.setLayoutParams(Rlparam2);
            mBottomManageMenuLayout.setVisibility(View.GONE);
            mBottomMainMenuLayout.setVisibility(View.VISIBLE);
            mMainLayout.setBackgroundColor(getColor(R.color.white));
            EventBus.getDefault().post(new MessageEvent(EventType.HIDE_FRAGMENT_DELETE_BTN));
        }
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getEventMessage(BaseEvent event) {
        //滑动事件
        if (event instanceof SlideEvent) {
            switch (((SlideEvent) event).getmEventType()) {
                case EventType.ACTION_DOWN:
                    switch (((SlideEvent) event).direction) {
                        case "left":
                            int cItem = mViewPager.getCurrentItem();
                            mViewPager.setCurrentItem(cItem > 0 ? cItem - 1 : cItem);
                            break;
                        case "right":
                            int rItem = mViewPager.getCurrentItem();
                            mViewPager.setCurrentItem(rItem + 1);
                            break;
                    }
                    break;
            }
        }
        //缩放事件
        else if (event instanceof ZoomEvent) {
            switch (((ZoomEvent) event).getmEventType()) {
                case EventType.FRAGMENT_RESTORE:
                    changeWindowSize();
                    break;
            }
        }
        //普通消息事件（显隐、增删）
        else if (event instanceof MessageEvent) {
            switch (((MessageEvent) event).getmEventType()) {
                case EventType.DELETE_SINGLE_FRAGMENT:
                    mMainViewPagerAdapeter.deleteSingleFragment(((MessageEvent) event).mFragmentTag, mViewPagerDataList);
                    break;
            }
        }
        //窗口标题改变事件
        else if (event instanceof ChangeTitleEvent) {
            AppInfoBean bean = (AppInfoBean) ((ChangeTitleEvent) event).mObject;
            mBottomTitleTv.setText(bean.appName);
            if (bean.appIconUri != null) {
                setTitleIcon(mBottomTitleIcon, bean.appIconUri);
            } else if (bean.appIconUrl != null) {
                setTitleIcon(mBottomTitleIcon, bean.appIconUrl);
            }

        }
    }


    /**
     * 设置标题图标
     *
     * @param imageView 需要设置图标的控件
     * @param url       Url图标的路径
     */
    private void setTitleIcon(ImageView imageView, String url) {
        ImageLoader.create(getContext())
                .loadUrl(url)
                .setFitCenter()
                .into(imageView);
    }

    /**
     * 设置标题图标
     *
     * @param imageView 需要设置图标的控件
     * @param uri       Uri图标的路径
     */
    private void setTitleIcon(ImageView imageView, Uri uri) {
        ImageLoader.create(getContext())
                .loadUri(uri)
                .setFitCenter()
                .into(imageView);
    }

}